package cn.com.callback

import cn.com.kh.HttpClientProxy
import cn.com.kh.KHDBConfig
import com.alibaba.fastjson.JSONObject
import com.aliyuncs.DefaultAcsClient
import com.aliyuncs.IAcsClient
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse
import com.aliyuncs.profile.DefaultProfile
import com.aliyuncs.profile.IClientProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.com.elite.EliteBean;

public class autoSendMessage implements CallBackInvoke {
    private static final Logger log = LoggerFactory.getLogger(autoSendMessage.class);

    public void doCallBack(EliteBean eliteBean, String callBack, Map map, String paramString) {

        log.warn("---autoSendMessage---");
        //查找待发送任务
        List getSmsSelectSQL = eliteBean.chaxun_sql("Select Documentout_Guid," +
                "       Doctype," +
                "       Documentpath," +
                "       Documentpath2," +
                "       Lockedby," +
                "       OpenId," +
                "       Template_Id," +
                "       Stringfield1," +
                "       Documentto" +
                "  From Documentout" +
                " Where Doctype In (3, 4, 5)" +
                "   And Status = 3" +
                "   And Trialcount < Trialcountlimit" +
                "   And Ifnull(Expectedstartdate, Now()) <= Now()" +
                " Order By Priority_Id, Expectedstartdate Limit 200", "dataSource");
        log.debug("SQL获取待发送数据量:" + getSmsSelectSQL.size());

        for (int i = 0; i < getSmsSelectSQL.size(); i++) {

            Map selectResultcm = getSmsSelectSQL.get(i);
            String Documentout_Guid = selectResultcm.get("Documentout_Guid");
            String Doctype = selectResultcm.get("Doctype");
            String Documentto = selectResultcm.get("Documentto");
            String Documentpath = selectResultcm.get("Documentpath");
            String Documentpath2 = selectResultcm.get("Documentpath2");
            String Template_Id = selectResultcm.get("Template_Id");
            String Open_Id = selectResultcm.get("OpenId");
            String URL = selectResultcm.get("Stringfield1");
            String opsource = selectResultcm.get("Lockedby");

            if (Doctype == "3") {
                doSendSMS(eliteBean, Documentout_Guid, Documentto, Documentpath2, Open_Id, Template_Id);

            } else if (Doctype == "4") {
                doSendWXGZH(eliteBean, Documentout_Guid, Open_Id, Template_Id, URL, Documentpath2, opsource);

            } else if (Doctype == "5") {
                doSendWXMiniP(eliteBean, Documentout_Guid, Open_Id, Template_Id, URL, Documentpath2, opsource);

            } else {
                log.warn("未知的消息类型-本条任务结束");
            }
        }

    }

    /**
     * 发送短信消息
     * @param s1
     * @param s2
     * @param s3
     */
    public static void doSendSMS(EliteBean eliteBean, String Documentout_Guid, String Documentto, String Documentpath2, String OpenId, String Template_Id) {

        // 开始准备发送
        JSONObject sendResultJson = sendAliSms(eliteBean, Documentout_Guid, Documentto, Documentpath2, OpenId, Template_Id);

        if (sendResultJson.getString("code") == "OK") {
            // 发送成功
            eliteBean.update("Update Documentout Set Status = '1', Trialcount = Trialcount + 1, Lasttrydatetime = Now(), Finishdatetime = Now() Where Documentout_Guid = '" + Documentout_Guid + "'", "dataSource");
        } else {
            // 发送失败
            String failCode = sendResultJson.getString("code");
            String failDesc = sendResultJson.getString("msg");
            eliteBean.update("Update Documentout Set Status = Case When Trialcount + 1 >= Trialcountlimit Then '-1' Else Status End, Failcode = '" + failCode + "', Faildescription = '" + failDesc + "', Trialcount = Trialcount + 1, Lasttrydatetime = Now() Where Documentout_Guid = '" + Documentout_Guid + "'", "dataSource");
        }

    }

    /**
     * 发送公众号消息
     * @param s1
     * @param s2
     */
    public static void doSendWXGZH(EliteBean eliteBean, String Documentout_Guid, String Open_Id, String Template_Id, String url, String Template_Data, String opsource) {
        int code = 0;
        String msgid = "";
        String msg = "";
        try {
            String apiWXSendTemplateURL = KHDBConfig.getAPIURL(eliteBean, "NGS-Local") + "/ngsapitask/api/apiWXSendTemplate?opsource=" + opsource;
            JSONObject postBody = new JSONObject();
            JSONObject postData = JSONObject.parseObject(Template_Data);
            postBody.put("touser", Open_Id);
            postBody.put("template_id", Template_Id);
            postBody.put("topcolor", "#FF0000");
            postBody.put("url", url);
            postBody.put("data", postData);
            log.debug("待发送公众号模板消息URL：" + apiWXSendTemplateURL + " 发送内容:" + postBody.toString());

            // 调用发送公众号模板接口
            String sendResult = HttpClientProxy.sendPost(apiWXSendTemplateURL, postBody.toString(), "", 5000);
            JSONObject sendResultJson = JSONObject.parseObject(sendResult);

            // 解析发送返回结果
            code = sendResultJson.getInteger("code");
            msg = sendResultJson.getString("msg");
            msgid = sendResultJson.getJSONObject("data").getString("msgid");
        } catch (Exception e1) {
            log.error("发送公众号模板处理异常", e1);
            code = -1;
        }

        if (code == 1) {
            // 发送成功
            eliteBean.update("Update Documentout Set Status = '1', Trialcount = Trialcount + 1, Lasttrydatetime = Now(), Finishdatetime = Now(), Msgid = '" + msgid + "' Where Documentout_Guid = '" + Documentout_Guid + "'", "dataSource");
        } else {
            // 发送失败
            eliteBean.update("Update Documentout Set Status = Case When Trialcount + 1 >= Trialcountlimit Then '-1' Else Status End, Failcode = '" + code + "', Faildescription = '" + msg + "', Trialcount = Trialcount + 1, Lasttrydatetime = Now() Where Documentout_Guid = '" + Documentout_Guid + "'", "dataSource");
        }
        log.debug("发送公众号模板处理完成...");

    }

    /**
     * 发送小程序消息
     * @param s1
     * @param s2
     */
    public static void doSendWXMiniP(EliteBean eliteBean, String Documentout_Guid, String Open_Id, String Template_Id, String url, String Template_Data, String opsource) {
        int code = 0;
        String msgid = "";
        String msg = "";
        try {
            String apiWXSendTemplateURL = KHDBConfig.getAPIURL(eliteBean, "NGS-Local") + "/ngsapitask/api/apiWXSendTemplate?opsource=" + opsource;
            JSONObject postBody = new JSONObject();
            JSONObject postData = JSONObject.parseObject(Template_Data);
            postBody.put("touser", Open_Id);
            postBody.put("template_id", Template_Id);
            postBody.put("miniprogram_state", "trial");
            postBody.put("lang", "zh_CN");
            postBody.put("page", url);
            postBody.put("data", postData);
            log.debug("待发送小程序消息URL：" + apiWXSendTemplateURL + " 发送内容:" + postBody.toString());

            // 调用发送公众号模板接口
            String sendResult = HttpClientProxy.sendPost(apiWXSendTemplateURL, postBody.toString(), "", 5000);
            JSONObject sendResultJson = JSONObject.parseObject(sendResult);

            // 解析发送返回结果
            code = sendResultJson.getInteger("code");
            msg = sendResultJson.getString("msg");
            msgid = sendResultJson.getJSONObject("data").getString("msgid");
        } catch (Exception e1) {
            log.error("发送小程序模板处理异常", e1);
            code = -1;
        }

        if (code == 1) {
            // 发送成功
            eliteBean.update("Update Documentout Set Status = '1', Trialcount = Trialcount + 1, Lasttrydatetime = Now(), Finishdatetime = Now(), Msgid = '" + msgid + "' Where Documentout_Guid = '" + Documentout_Guid + "'", "dataSource");
        } else {
            // 发送失败
            eliteBean.update("Update Documentout Set Status = Case When Trialcount + 1 >= Trialcountlimit Then '-1' Else Status End, Failcode = '" + code + "', Faildescription = '" + msg + "', Trialcount = Trialcount + 1, Lasttrydatetime = Now() Where Documentout_Guid = '" + Documentout_Guid + "'", "dataSource");
        }
        log.debug("发送小程序模板处理完成...");

    }

    public static JSONObject sendAliSms(EliteBean eliteBean, String Documentout_Guid, String Documentto, String Documentpath2, String OpenId, String Template_Id) {
        JSONObject resultSendSms = new JSONObject();

        log.debug("sendAliSms参数-Documentout_Guid:" + Documentout_Guid + " Documentto:" + Documentto + " Documentpath2:" + Documentpath2 + " OpenId:" + OpenId + " Template_Id:" + Template_Id);

        try {

            //产品名称:云通信短信API产品,开发者无需替换
            String product = "Dysmsapi";
            //产品域名,开发者无需替换
            String domain = "dysmsapi.aliyuncs.com";

            // 开发者自己的AK(在阿里云访问控制台寻找)
            String accessKeyId = KHDBConfig.getParam(eliteBean, "SMS-ID");
            String accessKeySecret = KHDBConfig.getParam(eliteBean, "SMS-KE");

            //可自助调整超时时间
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");
            log.debug("自助调整超时时间-Finish");

            //初始化acsClient,暂不支持region化
            IClientProfile profile = DefaultProfile.getProfile("cn-shenzhen", accessKeyId, accessKeySecret);
            DefaultProfile.addEndpoint("cn-shenzhen", "cn-shenzhen", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            log.debug("初始化acsClient-Finish");

            //组装请求对象-具体描述见控制台-文档部分内容
            SendSmsRequest request = new SendSmsRequest();
            //必填:待发送手机号
            request.setPhoneNumbers(Documentto);
            //必填:短信签名-可在短信控制台中找到
            request.setSignName(OpenId);
            //必填:短信模板-可在短信控制台中找到
            request.setTemplateCode(Template_Id);
            //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
            request.setTemplateParam(Documentpath2);

            //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
            request.setOutId(Documentout_Guid);
            log.debug("组装请求对象-Finish");

            //hint 此处可能会抛出异常，注意catch
            SendSmsResponse response = acsClient.getAcsResponse(request);
            log.debug("发送请求对象-Finish");
            log.debug("发送请求返回：" + response.toString());
            log.debug("发送请求返回getCode：" + response.getCode());
            log.debug("发送请求返回getMessage：" + response.getMessage());

            resultSendSms.put("code", response.getCode());
            resultSendSms.put("msg", response.getMessage());
            log.debug("调用阿里云短信发送结果：", resultSendSms.toString());

        } catch (Exception e1) {
            log.error("调用阿里云短信发送异常：", e1);
            resultSendSms.put("code", "-1");
            resultSendSms.put("msg", e1.getMessage());

        }

        return resultSendSms;
    }
}
